<?php

Raise::load('core.RaiseCollection');
Raise::load('core.reflection.RaiseVariable');

/**
 * RaiseDataTable class
 * A table that contains data in the form of rows and columns
 *
 * @author Sam-Mauris Yong / hellclanner at live dot com
 * @license http://www.opensource.org/licenses/bsd-license New BSD License
 * @package phpraise.core.structure
 * @since 1.2
 */
class RaiseDataTable extends RaiseCollection {
    
    /**
     * A collection of columns in the table
     * @var RaiseCollection
     */
    private $columns;

    /**
     * Create a new RaiseDataTable
     * @param RaiseCollection $c The collection to create the table columns from
     * @param RaiseCollection $d The collection to create the table cells / data from
     */
    public function __construct($c = null, $d = null){
        $this->columns = new RaiseCollection();
        if($c instanceof RaiseCollection){
            $this->columns = $c;
        }
        if($d instanceof RaiseCollection){
            $this->data($d->_a);
        }
    }

    /**
     * Get the columns of the table
     * @return RaiseCollection
     */
    public function columns(){
        return $this->columns;
    }

    /**
     * Add a RaiseCollection containing a new row with same columns as the table
     * @param RaiseCollection $row
     */
    public function add($row) {
        if(func_num_args() == 1 && is_array($row)){
            $row = new RaiseCollection($row);
        }
        if($row instanceof RaiseCollection && !($row instanceof RaiseDataTable)){
            // rearrange the row so that the column matches
            $d = array();
            foreach($this->columns() as $c){
                $d[] = $row->get($c);
            }
            $this->_a[] = $d;
            return;
        }
        throw new RaiseInvalidArgumentException('RaiseDataTable::add() expecting RaiseCollection as first parameter; ' . RaiseVariable::typeInfo($row) . ' was given instead.');
    }

    public function append($a) {
        if($a instanceof RaiseDataTable){
            if($a->columns()->equals($this->columns())){
                parent::append($a);
                return;
            }
        }
        throw new RaiseInvalidArgumentException('The argument passed to append to this RaiseDataTable is not a RaiseDataTable, or the RaiseDataTable does not have the same set of columns as this RaiseDataTable.');
    }

    public function prepend($a) {
        if($a instanceof RaiseDataTable){
            if($a->columns()->equals($this->columns())){
                parent::prepend($a);
                return;
            }
        }
        throw new RaiseInvalidArgumentException('The argument passed to prepend to this RaiseDataTable is not a RaiseDataTable, or the RaiseDataTable does not have the same set of columns as this RaiseDataTable.');
    }


}
